/*
* Some simple functions for populating lists
* Requires metadata.js for function createDoc
*/

function populateSelected(id, data) {
	var sel = $('#' +  id);
    sel.empty();
    for (var i=0; i<data.length; i++) {
      sel.append('<option value="' + data[i].id + '">' + data[i].title + '</option>');
    }
}

function populateList(id, data) {
	var sel = $('#' +  id);
    sel.empty();
    for (var i=0; i<data.length; i++) {
    	if(data[i].hasOwnProperty('children')) {
			// Element has children, create labels for these
			sel.append('<li id="' + data[i].id + '">' + data[i].title + '<ul id="' + id + '_' + data[i].id + '"></ul></li>');
			populateList(id + '_' + data[i].id, data[i].children, '','');
		} else {
			sel.append('<li id="' + data[i].id + '">' + data[i].title + '</li>');
		}
    }
}

function populatePagetypes(id, data) {
	var sel = $('#' +  id);
    sel.empty();
    for (var i=0; i<data.length; i++) {
      sel.append('<li id="' + data[i].id + '"><a onclick="changePagetype(' + i + ', metadata);">' + data[i].title + '</a></li>');
    }
}

function populateRadio(id, data, name) {
	var sel = $('#' +  id);
    sel.empty();
    for (var i=0; i<data.length; i++) {
    	var strId = data[i].id;
    	if (strId!=='') {
    		strId = ' (' + data[i].id + ')';
    	} 
		sel.append('<label class="radio"><input type="radio" name="' + name + '" value="' + data[i].id + '" id="' + data[i].id + '">' + data[i].title + strId + '</label>');
    }
}

function populateLabels(id, data, seperator, icon) {
	var sel = $('#' + id);

	if (icon===undefined) {
		icon='<i class="icon-plus icon-white">'
	}

	if (seperator===undefined) {
		seperator = '';
	}

	for (var i=0; i<data.length; i++) {
		if (data[i].hasOwnProperty('title')) {
			if(data[i].hasOwnProperty('children')) {
				icon = '<i class="icon-plus icon-white">';
				// Element has children, create labels for these
				sel.append('<span class="label label-default">' + data[i].title + ' ' + icon + '</i></span>&nbsp;<ul id="' + id + '_' + data[i].id + '"></ul>&nbsp;' +  seperator);	
				populateLabels(id + '_' + data[i].id, data[i].children, '','');
			} else {
				sel.append('<span class="label label-default">' + data[i].title + ' ' + icon + '</i></span>&nbsp;' +  seperator);	
			}
		    
		} else {
	    	sel.append('<span class="label label-default">' + data[i] + ' ' + icon + '</span>&nbsp;' +  seperator);
	    }
	}

	$('.labels span.label').off("click");
	listenLabels();
}

function createLetterRange(iLetterSplit) {
	var letters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','ä','ö','å'];
	var split = 0;
	var idNo = 0;
	var range = [];
	var currentRange = {};
	currentRange.letters = [];
	currentRange.id = 'cat_' + idNo;
		
	for (i=0;i<letters.length;i++) {

		if (split<iLetterSplit) {
			currentRange.letters.push(letters[i]);
			range[letters[i]] = currentRange.id;
			split += 1;
		} else {
			currentRange.letters.push(letters[i]);
			currentRange.title = currentRange.letters[0] + ' - ' + letters[i];
			range[letters[i]] = currentRange.id;

			range.push(currentRange);
			
			currentRange = {};
			currentRange.letters = [];
			idNo += 1;	
			currentRange.id = 'cat_' + idNo;
	
			split = 0;
		}
	}

	return range;
}

function populateLabelsAlphBlocks(id, data, seperator, icon, iLetterSplit) {
	var ranges = createLetterRange(iLetterSplit);
	var selParent = $('#' + id);

	if (icon===undefined) {
		icon='<i class="icon-plus icon-white">'
	}

	if (seperator===undefined) {
		seperator = '';
	}

	// Create rangelabels
	for (var i=0;i<ranges.length;i++) {
		    selParent.append('<h4 id="' + ranges[i].id + '"><i class="icon-plus"></i> ' + ranges[i].title 
		    	+ ' </h4><div class="hidden" id="items_' + ranges[i].id + '"></div>' +  seperator);

		    // Listen for click
		    $('#' + ranges[i].id).on('click',function(ev) {
				$('#items_' + this.id).toggleClass('hidden');
				$('i', this).toggleClass('icon-plus icon-minus');
		    });
	}

	for (var i=0; i<data.length; i++) {

		if (data[i].hasOwnProperty('title')) {
			var currentLetter = data[i].title.substr(0,1).toLowerCase();
			sel = $('#items_' + ranges[currentLetter]);
		    sel.append('<span class="label label-default">' + data[i].title + ' ' + icon + '</i></span>&nbsp;' +  seperator);
		} else {
	    	selParent.append('<span class="label label-default">' + data[i] + ' ' + icon + '</span>&nbsp;' +  seperator);
	    }
	}

	$('.labels span.label').off("click");

	listenLabels_AddToFilter();
}

function populateMenuAlphBlocks(id, data, seperator, icon, iLetterSplit) {
	var ranges = createLetterRange(iLetterSplit);
	var selParent = $('#' + id);

	if (icon===undefined) {
		icon='<i class="icon-plus-sign icon-white">'
	}

	if (seperator===undefined) {
		seperator = '';
	}

	// Create rangelabels
	for (var i=0;i<ranges.length;i++) {
		    selParent.append('<li id="' + ranges[i].id + '"><a><i class="icon-plus-sign icon-white"></i> ' + ranges[i].title 
		    	+ '</a> <ul id="items_' + ranges[i].id + '" class="hidden nav nav-tabs nav-stacked"></ul></li>' +  seperator);

		    // Listen for click
		    $('#' + ranges[i].id).on('click',function(ev) {
				$('#items_' + this.id).toggleClass('hidden');
				$('i', this).toggleClass('icon-plus-sign icon-minus-sign');
		    });
	}

	for (var i=0; i<data.length; i++) {

		if (data[i].hasOwnProperty('title')) {
			var currentLetter = data[i].title.substr(0,1).toLowerCase();
			sel = $('#items_' + ranges[currentLetter]);
		    sel.append('<li><a>' + data[i].title + '</li>' +  seperator);
		} else {
	    	selParent.append('<li>' + data[i] + ' ' + icon + '</li>&nbsp;' +  seperator);
	    }
	}
}

function listenLabels_AddToFilter() {
	$('.labels span.label').on('click', function(ev) {
		$(this).toggleClass('label-default label-success');
		$('i', this).toggleClass('icon-plus icon-minus');

		if (this.className.indexOf('label-success')>-1) {
			createLabels('filters-selected','',[this.innerText],'<br />');
		}
	});
}

function listenLabels() {
	$('.labels span').on('click', function(ev) {
		$(this).toggleClass('label-default label-success');
		$('i', this).toggleClass('icon-plus icon-minus');
		
	});
}

function addSources(id, data) {
	var sel = $(id);

	if (data.sources.length>0) {
		sel.append('<h4>Källor</h4>');
		sel.append('<ul id="' + data.id + '_sources"></ul>');
		sel = $('#' + data.id + '_sources');

		console.log('Source found for id #' + data.id);

		for (var i=0; i<data.sources.length; i++) {
			var source = data.sources[i];
			var title = '';

			if (source.title==='') {
				title = source.src;
			} else {
				title = source.title;
			}

			sel.append('<li><a href="' + source.src + '">' + title + '</a></li>');

			if (source.description!=='') {
				sel.append('<p>' + source.description + '</p>');
			}
		}
	}
}

/*
* Show/Hide fields depending on pagetype
*/

function changePagetype(iPageNumber, data) {

	var hideElements
		, page = data.pagetypes[iPageNumber]
	;

	// Hides all elements within certain tabs
	hideElements = function() {
		$('#cat .control-group').hide();
		$('.nav-pills li').hide();
	};

	hideElements();
	$('#currentpagetype').text(page.title);

	// Show fields relevant to pagetype
	for (var i=0; i<page.show.length; i++) {

		var objId = page.show[i];

		if (objId.indexOf('/')>-1) {
			// Field
			objId = objId.substr(objId.indexOf('/') + 1 , objId.length);
			$('#' + objId).parent().parent().show();
		} else {
			// Tab
			objId = objId + '_tab';
			$('#' + objId).show();
		}
	
	}

	// Set Focus on first tab
	$('.nav-pills a[href="#meta"]').tab('show');
}

/*
* Creates a documentation for data in metadata.js
*/

function createLabels(id, idFrom, data, seperator) {
	var from = $('#' + idFrom);
	var sel = $('#' + id);

	if (data===undefined) {
		data = from.val().split(',');
	}

	if (seperator==undefined) {
		seperator='';
	}

	for (var i=0; i<data.length; i++) {
	    sel.append('<span class="btn btn-primary">' + data[i] + ' <i class="icon-remove icon-white"></i></span>&nbsp;' + seperator);
	}

	$('#' + idFrom).val("");

	$('span.btn-primary').on('click', function(ev) {
		this.remove();
	});
}

function createDoc() {
	var data = metadata.lists;
	var doc = $('#doc');

	for (var i=0; i<data.length; i++) {
		var commentId = data[i].id + '_comments';
		var mainId = data[i].id + '_main';
		var itemsId = data[i].id + '_items';


		doc.append('<div class="row"></div>')
			.append('<section id="' + mainId + '" class="span6"></section>')
			.append('<aside id="' + commentId + '" class="span4"></aside>');

		var sel = $('#' + mainId);
		console.log('Doc: #' + data[i].id)
    	sel.append('<h3>' + data[i].title + '</h3>');
    	sel.append('<ul id="' + data[i].id + '_items"></ul>');
    	populateList(itemsId, metadata[data[i].id]);

    	if (data[i].description!=='') {
    		$('#' +  commentId).append('<h4>Kommentarer</h4>')
    		$('#' +  commentId).append('<p>' + data[i].description + '</p>')
    	}

    	addSources('#' + commentId, data[i]);
    }	
}

$('.labels .btn-info').on('click', function(ev) {
	this.remove();
});